<template>
    <div class="activity">
        <div class="header">
            <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
                <el-form-item label="活动名称">
                    <el-input v-model="queryInfo.name" placeholder="请输入活动名称" clearable @clear="getUserList()" />
                </el-form-item>
                <el-form-item label="渠道名称">
                    <el-select v-model="queryInfo.channelId" clearable placeholder="请选择渠道" @click="getChannelList">
                        <el-option v-for="item in channel" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="活动状态">
                    <el-select v-model="queryInfo.type" clearable placeholder="请选择活动状态">
                        <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="活动类型">
                    <el-select v-model="queryInfo.status" clearable placeholder="请选择活动类型">
                        <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="findActivityList"> <el-icon>
                            <Search />
                        </el-icon>搜索</el-button>
                    <el-button class="addBtn" @click="resetForm"> <el-icon>
                            <Refresh />
                        </el-icon>重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="nav">
            <el-button type="primary" plain @click="openUserDialog"><el-icon>
                    <Plus />
                </el-icon>新增</el-button>
            <el-button type="success" plain><el-icon>
                    <Edit />
                </el-icon>修改</el-button>
            <el-button type="danger" plain @click="deleteActivityAll"><el-icon>
                    <Delete />
                </el-icon>删除</el-button>
            <el-button type="warning" plain @click="activityExport"><el-icon>
                    <Download />
                </el-icon>导出</el-button>
        </div>
        <div class="toBe">
            <el-table :data="activity" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="channelId" label="活动编号" />
                <el-table-column prop="name" label="活动名称" />
                <el-table-column prop="channelName" label="渠道名称" />
                <el-table-column prop="info" label="活动简介" />
                <el-table-column label="活动类型">
                    <template #default="scope">
                        <el-tag type="primary" v-if="scope.row.type == 1">代金券</el-tag>
                        <el-tag type="success" v-if="scope.row.type == 2">折扣券</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="活动明细" />
                <el-table-column label="活动状态">
                    <template #default="scope">
                        <el-tag type="info" v-if="scope.row.status == 1">禁用</el-tag>
                        <el-tag type="primary" v-if="scope.row.status == 0">正常</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="活动起始时间" />
                <el-table-column prop="endTime" label="活动结束时间" />
                <el-table-column label="操作" min-width="150">
                    <template #default="scope">
                        <span class="l" @click="openDialog(scope.row.activityId)"><el-icon>
                                <Edit />
                            </el-icon>修改</span>
                        <span class="r" @click="handleDelete(scope.row.activityId)"><el-icon>
                                <Delete />
                            </el-icon>删除</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog v-model="dialogVisible" :title="id ? '编辑活动' : '添加活动'" width="800" :before-close="handleClose">
            <el-form :inline="true" ref="activityFormRef" :model="activityForm" :rules="rules" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="渠道来源" prop="channelId">
                    <el-select v-model="activityForm.channelId" clearable placeholder="请选择渠道" @click="getChannelList">
                        <el-option v-for="item in channel" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="活动名称" prop="name">
                    <el-input v-model="activityForm.name" placeholder="请输入活动名称" />
                </el-form-item>
                <el-form-item label="活动时间" prop="fundTimeArray">
                    <el-date-picker v-model="activityForm.fundTimeArray" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" range-separator="至" format="YYYY-MM-DD HH:mm:ss"
                        date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" />
                </el-form-item>
                <el-form-item label="活动简介" prop="info">
                    <el-input v-model="activityForm.info" placeholder="请输入活动简介" />
                </el-form-item>
                <el-form-item label="活动类型" prop="type">
                    <el-select v-model="activityForm.type" clearable placeholder="请选择活动类型">
                        <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button v-if="id" type="primary" @click="editActivityForm(activityFormRef)">编辑</el-button>
                    <el-button v-else type="success" @click="addActivityForm(activityFormRef)">添加</el-button>
                    <el-button @click="handleClose">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue';
import { activityList, channelList, addActivity, ActivityData, editActivity, ActivityDelete, findActivity, expostActivity } from "../../../api/activity/index"
import { ComponentSize, ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
const formSize = ref<ComponentSize>("default");
const activityFormRef = ref<FormInstance>();
const activityForm = reactive({
    activityId: 0,
    channelId: 0,
    name: "",
    info: "",
    beginTime: "",
    endTime: "",
    type: 0,
    fundTimeArray: []
});
const id = ref(0);

import { formdata } from "../../../utils/format"

watch(() => activityForm.fundTimeArray, (newVal) => {
    console.log(newVal)
    const formatTimeArray = ref([])
    newVal.forEach(el => {
        // console.log(el)
        formatTimeArray.value.push(formdata.formDate(el))
        activityForm.beginTime = formatTimeArray.value[0]
        activityForm.endTime = formatTimeArray.value[1]
    });
})
const rules = reactive<FormRules>({
    name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
    info: [{ required: true, message: "请输入活动简介", trigger: "blur" }],
    channelId: [
        {
            required: true,
            message: "请选择渠道来源",
            trigger: "change",
        },
    ],
    fundTimeArray: [
        {
            required: true,
            message: "请选择活动时间",
            trigger: "change",
        },
    ],
    type: [
        {
            required: true,
            message: "请选择活动类型",
            trigger: "change",
        },
    ],
});
const activityId = ref('')
const dialogVisible = ref(false)
const value = ref('')
const value1 = ref('')
const value2 = ref('')
const options1 = [
    {
        value: '1',
        label: '正常',
    },
    {
        value: '2',
        label: '禁用',
    }
]
const options2 = [
    {
        value: '2',
        label: '代金券',
    },
    {
        value: '1',
        label: '折扣券',
    }
]
const queryInfo = ref({
    name: "",
    status: "",
    channelId: "",
    type: "",
});
const channel = ref([])
const activity = ref([]);
const selectedActivities = ref([])
const openDialog = (data: any) => {
    id.value = data;
    ActivityData(data).then(res => {
        Object.entries(res.data).map((item) => {
            activityForm[item[0]] = item[1];
        })
        const newArr = []
        newArr.push(res.data.beginTime, res.data.endTime)
        activityForm.fundTimeArray = newArr
    })
    dialogVisible.value = true
    activityForm.activityId = data
}
const resetForm = () => {
    queryInfo.value.name = ""
    queryInfo.value.status = ''
    queryInfo.value.channelId = ''
    queryInfo.value.type = ''
};
const openUserDialog = () => {
    id.value = 0;
    dialogVisible.value = true
    activityForm.activityId = 0
    activityForm.channelId = 0
    activityForm.name = ""
    activityForm.info = ""
    activityForm.beginTime = ""
    activityForm.endTime = ""
    activityForm.type = 0
    activityForm.fundTimeArray = []
}
const addActivityForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            addActivity(activityForm).then((res: any) => {
                if (res.code != 200) return ElMessage.error("添加活动失败");
                ElMessage.success("添加活动成功");
                getActivityList();
                dialogVisible.value = false
            });
        } else {
            console.log("error submit!", fields);
        }
    });
};
const deleteActivityAll = () => {
    const ids = getSelectedActivityIds()
    ElMessageBox.confirm("是否确认删除活动编号为" + ids + "的数据项?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            ActivityDelete(ids).then((res: any) => {
                if (res.data.code != 200) return ElMessage.error("删除活动失败");
                ElMessage.success("删除活动成功");
                getActivityList();
            });
        })
        .catch(() => {
            ElMessage.info("取消删除");
        });

};
const activityExport = () => {
    expostActivity().then((res: any) => {
        if (res.data.code != 200) return ElMessage.error("导出活动失败");
        ElMessage.success("导出活动成功");
    });
}
const handleDelete = (data: any) => {
    ElMessageBox.confirm("是否确认删除活动编号为" + data + "的数据项?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            ActivityDelete(data).then((res: any) => {
                if (res.code != 200) return ElMessage.error("删除活动失败");
                ElMessage.success("删除活动成功");
                getActivityList();
            });
        })
        .catch(() => {
            ElMessage.info("取消删除");
        });
}
const editActivityForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            editActivity(activityForm).then((res: any) => {
                if (res.code != 200) return ElMessage.error("修改活动失败");
                ElMessage.success("修改活动成功");
                getActivityList();
                dialogVisible.value = false
            });
        } else {
            console.log("error submit!", fields);
        }
    });
};
const findActivityList = () => {
    findActivity(queryInfo.value).then((res: any) => {
        if (res.code != 200) return ElMessage.error("查询活动失败");
        activity.value = res.rows;
    });
}
const getActivityList = () => {
    activityList().then((res: any) => {
        if (res.code != 200) return ElMessage.error("查询活动失败");
        activity.value = res.rows;
    });
}
const getChannelList = () => {
    channelList().then((res: any) => {
        if (res.code != 200) return ElMessage.error("查询渠道失败");
        channel.value = res.data.map(item => ({
            value: item.channelId,
            label: item.channelName
        }));
    });
}
const handleSelectionChange = (selection) => {
    selectedActivities.value = selection;
}
const getSelectedActivityIds = () => {
    const activityIds = selectedActivities.value.map(item => item.activityId);
    return activityIds.join(',');
}
const handleClose = (done: () => void) => {
    ElMessageBox.confirm('确定要关闭吗?')
        .then(() => {
            done()
        })
        .catch(() => {
            // catch error
        })
}
onMounted(() => {
    getActivityList();
})
</script>

<style scoped lang="scss">
.activity {
    width: 100%;
    height: 100%;
    padding: 20px;

    .header {

        i {
            margin-right: 10px;
        }
    }

    .nav {
        margin-bottom: 10px;

        i {
            margin-right: 10px;
        }
    }

    .toBe {
        margin-bottom: 20px;

        .l,
        .r {
            color: #409dfe;
            cursor: pointer;
            display: inline-block;

            i {
                padding-top: 4px;
            }
        }

        .r {
            margin-left: 10px;
        }
    }
}
</style>